package evs.gateway;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import evs.location.EvsException;
import evs.security.SecureServlet;

public class IndexGatewayServlet extends SecureServlet {

	private static final long serialVersionUID = 5225298996573246817L;
	
	private String _centralIndexUrl; 
	
	@Override
    public void init() throws ServletException
    {
        super.init();
        
        String configFilePath = this.getInitParameter("gateway-config-file");
    
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream( configFilePath );
        
        if ( stream == null )
        {
            throw new ServletException( "Could not find configuration file for IndexServlet!" );
        }
        
        try
        {
            Document xml = Util.getDocumentFromStream( stream );
            
            NodeList nodes = xml.getElementsByTagName("index-url");
            
            if ( nodes.getLength() != 1 )
            {
            	throw new ServletException( "IndexGateway - Config file does not contain url of CentralIndex!" );
            }
            
            _centralIndexUrl = nodes.item(0).getTextContent();
        } 
        catch ( EvsException e )
        {
            throw new ServletException( e );
        }
        finally
        {
            if ( stream != null )
            {
                try
                {
                    stream.close();
                }
                catch ( IOException e )
                {    
                }
            }
        }
    }
	
	@Override
	protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException
	{
		try {
		    if ( !_authenticate( request ) )
		    {
		        response.sendError( HttpServletResponse.SC_FORBIDDEN, "Failed to authenticate request!" );
		        return;
		    }
		    
		    if ( request.getHeader( "x-source-service" ) == null )
            {
		        response.sendError( HttpServletResponse.SC_BAD_REQUEST, "x-source-service header missing" );
		        return;
            }
		    
		    String indexResponse = _http.get( _centralIndexUrl, "application/xml" );
		    
		    String encrypted = _securityManager.encrypt( indexResponse, request.getHeader( "x-source-service" ) );
		    
		    response.getWriter().write( encrypted );
		} 
		catch (IOException e) 
		{
			throw new ServletException( e );
		}
	}

    private boolean _authenticate( HttpServletRequest request )
    {
        String nonce = request.getParameter( "nonce" );
        String encryptedNonce = request.getParameter( "encryptedNonce" );
        
        if ( nonce == null || encryptedNonce == null )
            return false;
        
        String decryptedNonce = _securityManager.decrypt( encryptedNonce, request.getHeader( "x-source-service" ) );
        
        return decryptedNonce.equals( nonce );
    }

    @Override
    protected boolean _allowOnlyLocalAccess()
    {
        return false;
    }
}
